function mle = SMLE_v2(params,data,random_draws, num_drugs, num_periods, id, outside, S)
%SMLE Computes likelihood function given data and parameter guess

%     delta = params(1:3);
%     
%     alpha = params(4);
%     gamma = params(5);
%     sigma = 0; %params(6);

    delta = [-0.8235;-0.0585;-1.3565];
    alpha = 0.0258;
    gamma = params(1);
    sigma = params(2); %-0.9098; %-0.9098; %params(6); 


    
    random_draws = random_draws * sigma;
    
    % STEP 1: transform data into ID, quarter u_ij based on parameters
    % Basic_part: drug quality - alpha * copay
    u = delta(data(:,3)) - ...
        alpha * data(:,5) + gamma * data(:,6);
    % repmat sideways and add random draw rows
    u = repmat(u,1,S) + random_draws(data(:,3) + num_drugs * (data(:,1) - 1), :);
    
    % STEP 2: aggregate and compute SMLE
    eu = exp(u);
    probs = zeros(size(outside,1),S);
    
    for i=1:S
        groupsum = 1 + accumarray(id, eu(:,i));
        eu_chosen = eu(:,i) .* data(:,4);
        chosen_sum = accumarray(id,eu_chosen);
        p = ((1 - outside) .* chosen_sum + outside * 1) ./ groupsum;
        
        probs(:,i) = p;
    end

    
    mean_probs= mean(probs,2);
    mle = sum(log(mean_probs));
end

